package com.forg.mvc.core.container;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.forg.mvc.core.annotation.Controller;
import com.forg.mvc.core.common.ClassUtil;
import com.forg.mvc.core.common.Constant;
import com.forg.mvc.core.common.PropUtil;

public class CtrlCntr {

	private static List<Class<?>> ctrlClassList = new ArrayList<>();
	
	//单例 非线程安全
	public static Map<Class<?>, Object> controllerInstance = new HashMap<>();
	
	private static Logger logger = LoggerFactory.getLogger(CtrlCntr.class);
	
	public synchronized static boolean init(){
		
		if(ctrlClassList.isEmpty()){
			
			ctrlClassList = ClassUtil.getAnnotationClassList(Controller.class);
			
			return !ctrlClassList.isEmpty();
		}
		
		return true;
	}

	public static List<Class<?>> getCtrlClassList() {
		return ctrlClassList;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getInstance(Class<T> clazz){
		if(controllerInstance.get(clazz) == null){
			try {
				T t = clazz.newInstance();
				controllerInstance.put(clazz, t);
				
				logger.debug("create controller {} instance success.",clazz.getName());
				return t;
			} catch (Exception e) {
				throw new RuntimeException("instance controller error!",e);
			}
		}else{
			return (T)controllerInstance.get(clazz);
		}
	}

}
